package com.cyy.maven.core.aspect;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author: Cyy
 * @Description: 织入类
 * @Date:Created in 16:00 2018/7/22
 */
@Slf4j
@Aspect
@Component
public class LoggingAspect {

    @Pointcut("execution(* com.cyy.maven.core.service.impl.*.*(..))")
    private void log() {}

    @Before("log()")
    public void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        log.info("The method={} begins with={}", methodName, Arrays.asList(args));
    }

    @After("log()")
    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        log.info("The method={} ends", methodName);
    }

    @AfterReturning(pointcut = "log()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        log.info("The method={} ends with={}", methodName, result);
    }

    @AfterThrowing(pointcut = "log()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
        String methodName = joinPoint.getSignature().getName();
        log.error("The method={} occurs excetion:={}", methodName, e);
    }

    // @Around("log()")
    public Object aroundMethod(ProceedingJoinPoint pjd) {
        Object result = null;
        String methodName = pjd.getSignature().getName();
        try {
            // 前置通知
            log.info("The method={} begins with={}", methodName, Arrays.asList(pjd.getArgs()));
            // 执行目标方法
            result = pjd.proceed();
            // 返回通知
            log.info("The method={} ends with={}", methodName, result);
        } catch (Throwable e) {
            // 异常通知
            log.info("The method={} occurs exception:={}", methodName, e);
            throw new RuntimeException(e);
        }
        // 后置通知
        log.info("The method={} ends", methodName);
        return result;
    }
}